import {patch, cascade, fetch} from '../../../utils/axios'

const state = {
  name: '编辑资源',
  fields: {},
  valid: null,
  ipRules: [
    (v) => !!v || '请输入IP地址'
  ],
  msg: {
    ipAddress: '',
    subnet: '',
    gateway: ''
  }
}

const mutations = {
  editIps (state, payload) {
    if (payload.validate()) {
      var url = '/ips/' + state.fields.id + '/'
      patch(url,
        state.fields
      ).then((response) => {
        this._vm.$data.$$state.listips.editdialog = false
      }).catch((error) => {
        if (error.response) {
          let datas = error.response.data
          for (var name in datas) {
            state.msg[name] = datas[name]
          }
        }
      })
    }
  },
  deleteIps (state) {
    let r = confirm('确认删除？')
    if (r === true) {
      var url = '/ips/' + state.fields.id + '/'
      cascade(url).then((response) => {
        this._vm.$data.$$state.listips.editdialog = false
      }).catch((error) => {
        console.log(error.response.data.detail)
      })
    }
  },
  closeEditIps (state) {
    this._vm.$data.$$state.listips.editdialog = false
    let msg = this.msg
    for (var i in msg) {
      msg[i] = ''
    }
  },
  loadEditIps (state, payload) {
    let url = '/ips/' + payload + '/'
    fetch(url, {
    }).then((response) => {
      state.fields = response
    }).catch((error) => {
      alert(error.response)
    })
  }
}

const actions = {
  editIps ({commit, state}, payload) {
    commit('editIps', payload)
  },
  deleteIps ({commit}) {
    commit('deleteIps')
  },
  closeEditIps ({commit}) {
    commit('closeEditIps')
  },
  loadEditIps ({commit}, payload) {
    commit('loadEditIps', payload)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
